package branch_access;

import java.io.IOException;
import java.net.UnknownHostException;

import mware_lib.communication.Client;
import mware_lib.exceptions.IllegalMessageException;
import mware_lib.exceptions.RemoteException;
import mware_lib.messages.ReqManMsg;
import mware_lib.messages.RetManMsg;

public class ManagerProxy extends Manager {

	private String skelHost;
	private int skelPort;

	public ManagerProxy(String host, int port) {
		this.skelHost = host;
		this.skelPort = port;
	}

	@Override
	public String createAccount(String owner) {
		String ret = null;
		try {
			System.out.println("Connecting to: " + skelHost +" : " +skelPort);
			Client c = new Client(skelHost, skelPort);
			ReqManMsg reqMsg = new ReqManMsg("createAccount", owner);
			c.send(reqMsg);
			Object result = c.receive();
			if (result instanceof RetManMsg) {
				result = ((RetManMsg) result).getResult();
				if(result == null){
					return null;
				}
				if (result instanceof String) {
					ret = (String) result;
				}else {
					throw (Exception) result;
				}
			} else {
				throw new IllegalMessageException("expected a RetManMsg");
			}
		} catch (RuntimeException re){	//RuntimeException an den Benutzer weiterleiten
			throw re;
		} catch (Exception e) {
		
			//e.printStackTrace();
			System.out.println((e.getClass().toString() + ": " + e.getMessage()));
		}

		return ret;
	}

	@Override
	public boolean removeAccount(String accountID) {
		boolean ret = false;
		try {
			Client c = new Client(skelHost, skelPort);
			ReqManMsg invMsg = new ReqManMsg("removeAccount", accountID);
			c.send(invMsg);
			Object result = c.receive();
			if (result instanceof RetManMsg) {
				result = ((RetManMsg) result).getResult();
				if (result instanceof Boolean) {
					ret = (Boolean) result;
				}else {
					throw (Exception) result;
				}
			} else {
				throw new IllegalMessageException("expected a RetManMsg");
			}
		} catch (RuntimeException re){	//RuntimeException an den Benutzer weiterleiten
			throw re;
		} catch (Exception e) {
			//e.printStackTrace();
			System.out.println((e.getClass().toString() + ": " + e.getMessage()));
		}
		return ret;
	}

}
